import {
  getProductInspectionOrderList,
  addProductInspectionOrder,
  updateProductInspectionOrder,
  updateProductInspectionOrderStatus,
  productInspectionOrderRework,
  productInspectionOrderScrap
} from "@/api/productionManagement/productInspectionForm.js";

import { formatDate } from "@/uitils/publicMethod.js"
export const myMethod = {
  formatDate,
  // 排序
  sortChange(val) {},
  // 选中表格数据
  tableSelectionChange(val) {
    this.tableSelection = val;
    console.log(val);
  },
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 调整状态显示文案和样式
  getAuditStatus(val) {
    // 1 审核通过   0 审核不通过    null 未审核
    // 目前只有三种状态 对象最后一个元素代表null的状态，后续有新增请在对应的倒数第二个位置添加
    const typeObj = {
      0: "danger",
      1: "primary",
      2: "warning",
    };
    const infoObj = {
      0: "审核失败",
      1: "审核成功",
      2: "未审核",
    };
    return {
      type:
        val !== null
          ? typeObj[val]
          : typeObj[Object.keys(typeObj)[Object.keys(typeObj).length - 1]],
      info:
        val !== null
          ? infoObj[val]
          : infoObj[Object.keys(infoObj)[Object.keys(infoObj).length - 1]],
    };
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 清空弹框的数据
  closeChange() {
    this.detailInfo = {}
    this.$refs.addFormRef.resetForm()
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { WorkOrderCode } = this.form;
      const params = {
        ProductInspectionCode: WorkOrderCode || "", // 产品检验订单编号
        rows: this.pageSize,
        page: this.currentPage,
      };
      const res = await getProductInspectionOrderList(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  // 点击审核操作
  async auditChange(type) {
    if (this.tableSelection.length == 0) {
      return this.$message.error("请选择要审批的行!");
    }
    if (this.tableSelection.length != 1) {
      return this.$message.error("只能选择一行数据进行审批!");
    }
    // null 未审核   0 审核失败   1 审核成功
    if (this.tableSelection[0].status === 1) {
      const approver = `已经审批的产品检验单${this.tableSelection[0].productInspectionCode}不允许重复审批!`;
      return this.$message.error(approver);
    }
    this.selectAuditType = type;
    try {
      const params = {
        productInspectionId: this.tableSelection[0].productInspectionId, // 产品检验单Id
        status: this.selectAuditType, // 状态 0是放审 1是审核 2是删除
      };
      const result = await updateProductInspectionOrderStatus(params);
      console.log(result);
      if (result.ok) {
        this.$message.success("审核成功");
        // 清空查询条件
        this.tableSelection = []
        this.resetPage();
        // 刷新列表数据
        this.getTableData();
      } else {
        this.$message.error((result.err && result.err.msg) || "审核失败");
      }
    } catch (err) {
      console.error("数据异常", err);
    }
  },
  addChange() {
    this.addTitle = "添加产品检验单";
    this.$refs.addDialogComRef.dialogVisible = true;
    // 获取下拉框列表数据
    this.processData();
    this.$nextTick(()=> {
      // 检验时间默认当前
      this.$refs.addFormRef.forms.productInspectionTime = this.formatDate(new Date())
    })
  },
  // 获取检验项目列表数据
  async getInspectionProjectList() {
    const params = {
      QualityDetectionProjectCode: "",
      QualityDetectionProjectName: "",
      rows: 1000,
      page: 1,
    };
    const query = new URLSearchParams(params).toString();
    const url = `/api/QualityDetection/GetQualityDetectionProjectList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取检验指标列表数据
  async getInspectionIndicatorsList() {
    const params = {
      QualityDetectionIndicatorId: "",
      QualityDetectionIndicatorCode: "",
      QualityDetectionIndicatorName: "",
      rows: 1000,
      page: 1,
    };
    const query = new URLSearchParams(params).toString();
    const url = `/api/QualityDetection/GetQualityDetectionIndicatorList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取检验员
  async getInspectorsList() {
    const params ={
      page: 1,
      rows: 1000,
      sort: 'CreateDate',
      order: 'desc',
      wheres: JSON.stringify([])
    }
    const url = `/api/Employees/getPageData`;
    return this.http
      .post(url, params, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  // 获取质量检验方案
  async getDetectionInspectionPlanList() {
    const params = {
      rows: 10000,
      page: 1,
    };
    const query = new URLSearchParams(params).toString();
    const url = `/api/QualityDetection/GetQualityDetectionInspectionPlanList?${query}`;
    return this.http
      .get(url, {}, true)
      .then((res) => (res.status === 0 ? res.rows : false));
  },
  async processData() {
    this.$refs.addDialogComRef.loading = true;
    try {
      const [data1, data2, data3, data4] = await Promise.all([
        this.getInspectionProjectList(),
        this.getInspectionIndicatorsList(),
        this.getInspectorsList(),
        this.getDetectionInspectionPlanList()
      ]);
      this.$refs.addFormRef.inspectionProjectDataTemp = data1 ? JSON.parse(JSON.stringify(data1)) : [];
      this.$refs.addFormRef.inspectionIndicatorsDataTemp = data2 ? JSON.parse(JSON.stringify(data2)) : [];
      this.$refs.addFormRef.employeeOptions = data3 ? JSON.parse(JSON.stringify(data3)) : [];
      this.$refs.addFormRef.detectionInspectionPlanOptions = data4 ? JSON.parse(JSON.stringify(data4)) : [];
      // 质检方案有数据且编辑下 质检方案编码回显
      if(data4 && data4.length > 0 && this.$refs.addFormRef.forms.productInspectionId && this.$refs.addFormRef.forms.qualityDetectionInspectionPlanId) {
        this.$refs.addFormRef.forms.qualityDetectionInspectionPlanCode = data4.filter(item=> item.qualityDetectionInspectionPlanId === this.$refs.addFormRef.forms.qualityDetectionInspectionPlanId)[0].qualityDetectionInspectionPlanCode
      }
      this.$refs.addDialogComRef.loading = false;
    } catch (error) {
      this.$refs.addDialogComRef.loading = false;
      console.error("获取数据失败:", error);
    }
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.addFormRef.confirmChange();
  },
  async okChange() {
    console.log('通过校验');
    // return;
    try {
        this.$refs.addDialogComRef.loading = true;
        const {
        productInspectionCode,
        productPlanCode,
        productInspectionTime,
        qualityDetectionInspectionPlanId,
        inventoryId,
        inspectionQuantity,
        inspectionMethod,
        spotCheckRule,
        spotCheckRate,
        spotCheckQuantity,
        inspectionId,
        qualifiedQuantity,
        unQualifiedQuantity,
        receiveQualifiedQuantity,
        remark,
        } = this.$refs.addFormRef.forms;
        const params = {
          "productInspectionCode": productInspectionCode || '', // 产品检验订单编号
          "productPlanCode": productPlanCode, // 报检单号(生产订单号)
          "productInspectionTime": productInspectionTime, // 检验时间
          "qualityDetectionInspectionPlanId":qualityDetectionInspectionPlanId, // 质检检验方案Id
          "inventoryId": inventoryId, // 存货Id
          "inspectionQuantity": inspectionQuantity, // 报检数量
          "inspectionMethod": inspectionMethod, // 检验方式 1全检 2破坏性抽检 3非破坏性抽检
          "spotCheckRule": spotCheckRule, // 抽检规则 1比例 2定量
          "spotCheckRate": spotCheckRule === 2 ? 0 : spotCheckRate, // 抽检率
          "spotCheckQuantity": spotCheckQuantity, // 抽检数量
          "inspectionId": inspectionId, // 抽检人Id/员工Id
          "qualifiedQuantity": qualifiedQuantity, // 合格数
          "unQualifiedQuantity": unQualifiedQuantity, // 不合格数
          "receiveQualifiedQuantity": receiveQualifiedQuantity, // 合格数接收数量
          "remark": remark, // 备注
          "qualityDetectionInspectionPlanDetail": this.$refs.addFormRef.qualityDetectionInspectionPlanDetails.map((item) => {
            return {
                qualityDetectionIndicatorId:
                item.qualityDetectionIndicatorId,
                qualityDetectionProjectId: item.qualityDetectionProjectId,
            };
            }), // 检验项目检验指标集合array
        }
        const isAdd = !this.$refs.addFormRef.forms.productInspectionId;
        const text = isAdd ? "添加" : "修改";
        if (!isAdd) {
        params.productInspectionId =
            this.$refs.addFormRef.forms.productInspectionId;
        }
        const apiName = isAdd ? addProductInspectionOrder : updateProductInspectionOrder;
        const result = await apiName(params);
        if (result.ok) {
          this.$message.success(text + "成功");
          this.$refs.addDialogComRef.dialogVisible = false;
          if (isAdd) this.currentPage = 1;
          this.closeChange();
          this.getTableData();
        } else {
          this.$message.error(
              (result.err && result.err.msg) || text + "失败"
          );
        }
        this.$refs.addDialogComRef.loading = false;
    } catch (err) {
        this.$refs.addDialogComRef.loading = false;
        console.error("数据异常:", err);
    }
  },
  detailChange(val) {
    this.updateChange(val);
  },
  updateChange(val) {
    this.detailInfo = JSON.parse(JSON.stringify(val));
    this.addTitle = "修改产品检验单";
    this.$refs.addDialogComRef.dialogVisible = true;
    // 如果抽检规则 为 2定量，抽检率为空不需要填写
    if(val.spotCheckRule===2) val.spotCheckRate = null
    this.$nextTick(() => {
      this.$refs.addFormRef.forms = JSON.parse(JSON.stringify(val));
      this.$refs.addFormRef.qualityDetectionInspectionPlanDetails =
      this.$refs.addFormRef.forms.qualityDetectionInspectionPlanDetails.map(
        (item, index) => {
          return {
            key: index,
            qualityDetectionProjectId: item.qualityDetectionProjectId,
            qualityDetectionIndicatorId: item.qualityDetectionIndicatorId,
          };
        }
      );
    });
    // 获取下拉框列表数据
    this.processData();
  },
  async deleteChange(val) {
    // 审核成功不允许删除
    if(val.status === 1) {
      const approver = `已经审批通过的产品检验单${val.productInspectionCode}不允许删除!`;
      return this.$message.error(approver);
    }
    // 切换页码
    const oldCurrentPage = this.currentPage;
    const temp = Math.ceil(Math.max(this.totalPage - 1, 1) / this.pageSize);
    if (this.currentPage > temp) {
      this.currentPage = temp;
    }
    this.$refs.dataTableRef.tableLoading = true;
    try {
       const params = {
        productInspectionId: val.productInspectionId, // 产品检验单Id
        status: 2, // 状态 0是放审 1是审核 2是删除
      };
      const res = await updateProductInspectionOrderStatus(params);
      if (res.ok) {
        this.$message.success("删除成功");
        this.getTableData();
      } else {
        this.currentPage = oldCurrentPage;
        this.$message.error((res.err&&res.err.msg) || "删除失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.currentPage = oldCurrentPage;
      this.$message.error((err.err&&err.err.msg) || "删除失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  // 取消返工 报废
  closeOrderReworkChange() {
    this.orderReworkNumber = null
    this.$refs.orderReworkDialogComRef.dialogVisible = false
  },
  async orderReworkChange(type) { // 1返工 2报废
    this.orderReworkTitle = type === 1 ? '返工' : '报废'
    this.$refs.orderReworkDialogComRef.dialogVisible = true
  },
  async confirmOrderReworkChange() {
    if(!this.orderReworkNumber&&this.orderReworkNumber!==0){
      return this.$message.warning(`请输入${this.orderReworkTitle}数量`);
    }
    try {
      this.$refs.orderReworkDialogComRef.loading = true;
      let params = {}
      if(this.orderReworkTitle === '返工'){
        params = {
          productInspectionId: this.detailInfo.productInspectionId, // 产品检验单Id
          reworkQuantity: this.orderReworkNumber, // 数量
        };
      } else {
        params = {
          productInspectionId: this.detailInfo.productInspectionId, // 产品检验单Id
          scrapQuantity: this.orderReworkNumber, // 数量
        };
      }
      const apiName = this.orderReworkTitle === '返工' ? productInspectionOrderRework : productInspectionOrderScrap
      const res = await apiName(params);
      if (res.ok) {
        this.$message.success(`${this.orderReworkTitle}成功`);
        this.closeOrderReworkChange();
        this.$refs.addDialogComRef.dialogVisible = false;
        this.closeChange();
        this.getTableData();
      } else {
        this.$message.error((res.err&&res.err.msg) || `${this.orderReworkTitle}失败`);
      }
      this.$refs.orderReworkDialogComRef.loading = false
    } catch (err) {
      this.$message.error((err.err&&err.err.msg) || `${this.orderReworkTitle}失败`);
      this.$refs.orderReworkDialogComRef.loading = false
    }
  },
};
